package simtester.cloud

import java.util.concurrent.TimeUnit
import net.schmizz.sshj.SSHClient
import net.schmizz.sshj.common.IOUtils
import net.schmizz.sshj.connection.channel.direct.Session
import net.schmizz.sshj.connection.channel.direct.Session.Command

class CloudSession {

    private session
    
    CloudSession(SSHClient ssh) {
        session = ssh.startSession()
    }
    
    def exec(opts = [:], commandString) {
        opts.timeout = opts.timeout ?: 10
        
        println "CMD: [$commandString]"
        final Command cmd = session.exec(commandString)
        def output = IOUtils.readFully(cmd.getInputStream()).toString().trim()
        cmd.join(opts.timeout, TimeUnit.SECONDS)
        
        return output
    }
    
    def execAsync(commandString) {
        println "CMD: [$commandString]"
        session.exec(commandString)
    }
    
    void close() {
        session.close()
    }
}
